package com.ruoyi.file.ocrUnits;


import com.alibaba.fastjson.JSON;

import com.ruoyi.file.pojo.DrivingLicenseInfo;
import com.ruoyi.file.pojo.IdCardInfo;
import com.ruoyi.file.pojo.VehicleLicenseInfo;
import org.springframework.web.multipart.MultipartFile;

import java.net.URLEncoder;
import java.util.Map;

/**
* 身份证识别
*/
public class OcrUnit {
    /**
    * 重要提示代码中所需工具类
    * FileUtil,Base64Util,HttpUtil,GsonUtils请从
    * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
    * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
    * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
    * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
    * 下载
    */
    public static String ocrIdentification(Integer cardType, MultipartFile file) {
        String ak = "2iqK8HHoPgQ4lk8Vxbb5e24b";
        String sk = "BglemDhoJB3EpRKunQGZ1THY7X8qiSD0";
        // 请求url
        String url = "";
        if (cardType == 1 ){
            //身份证
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
        }else if (cardType == 2){
            //驾驶证
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license";
        }else if (cardType == 3){
            //行驶证
            url = "https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license";
        }
        try {
            // 从上传的文件中读取数据
            byte[] imgData = file.getBytes();
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "id_card_side=" + "front"
                    + "&image=" + imgParam
                    + "&detect_direction=true"      // 自动检测图像方向
                    + "&detect_risk=true";          // 检测风险（如翻拍、PS）

            // 获取有效的 access_token
            String accessToken = getAccessToken(ak, sk);

            if (accessToken == null) {
                System.out.println("获取 access_token 失败");
                return null;
            }

            String result = HttpUtil.post(url, accessToken, param);
            System.out.println("原始结果: " + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 获取百度AI的access_token
     * @param ak API Key
     * @param sk Secret Key
     * @return access_token
     */
    private static String getAccessToken(String ak, String sk) {
        try {
            // 获取token的URL
            String authUrl = "https://aip.baidubce.com/oauth/2.0/token";

            // 构造请求参数
            String param = "grant_type=client_credentials" +
                    "&client_id=" + ak +
                    "&client_secret=" + sk;

            // 发送请求获取token
            // 发送POST请求获取token
            String response = HttpUtil.post(authUrl, null, param);
            // 这里需要解析返回的JSON获取access_token
            // 假设返回格式为: {"access_token":"25.xxxxxxx","expires_in":2592000,...}
            // 如果你有GsonUtils，可以使用它来解析
            // 示例解析（你需要根据实际的工具类调整）:
            // Map<String, String> resultMap = GsonUtils.fromJson(response, Map.class);
            // return resultMap.get("access_token");

            // 临时解决方案：简单字符串解析（仅作示例）
            // 使用 GsonUtils 解析（如果可用）
            Map<String, Object> resultMap = GsonUtils.fromJson(response, Map.class);
            return JSON.toJSONString(resultMap.get("access_token"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解析返回数据
     * */
    public static IdCardInfo parseIdCardInfo (String idCardResult) {
        try {
            // 将外层JSON字符串转换为Map
            Map<String, Object> outerMap = GsonUtils.fromJson(idCardResult, Map.class);

            // 获取words_result部分
            Map<String, Object> wordsResult = (Map<String, Object>) outerMap.get("words_result");

            // 提取各个字段信息
            IdCardInfo idCardInfo = new IdCardInfo();
            idCardInfo.setName(getWordsValue(wordsResult, "姓名"));
            idCardInfo.setSex(getWordsValue(wordsResult, "性别"));
            idCardInfo.setNation(getWordsValue(wordsResult, "民族"));
            String birthday = getWordsValue(wordsResult, "出生");
            idCardInfo.setBirth(formatDate(birthday));
            idCardInfo.setAddress(getWordsValue(wordsResult, "住址"));
            idCardInfo.setIdNumber(getWordsValue(wordsResult, "公民身份号码"));
            return idCardInfo;
        } catch (Exception e) {
            System.out.println("解析身份证信息时发生错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 驾驶证信息解析
     */
    public static DrivingLicenseInfo parseDrivingLicenseInfo(String drivingLicenseResult) {
        try {
            // 将外层JSON字符串转换为Map
            Map<String, Object> outerMap = GsonUtils.fromJson(drivingLicenseResult, Map.class);

            // 获取words_result部分
            Map<String, Object> wordsResult = (Map<String, Object>) outerMap.get("words_result");

            // 提取各个字段信息
            DrivingLicenseInfo licenseInfo = new DrivingLicenseInfo();
            licenseInfo.setCardNumber(getWordsValue(wordsResult, "证号"));
            licenseInfo.setName(getWordsValue(wordsResult, "姓名"));
            licenseInfo.setSex(getWordsValue(wordsResult, "性别"));
            licenseInfo.setNationality(getWordsValue(wordsResult, "国籍"));
            licenseInfo.setAddress(getWordsValue(wordsResult, "住址"));
            String birthday = getWordsValue(wordsResult, "出生日期");
            licenseInfo.setBirthDate(formatDate(birthday));
            String issueDate = getWordsValue(wordsResult, "初次领证日期");
            licenseInfo.setIssueDate(formatDate(issueDate));
            licenseInfo.setVehicleType(getWordsValue(wordsResult, "准驾车型"));
            licenseInfo.setValidFrom(getWordsValue(wordsResult, "有效期限始"));
            licenseInfo.setValidTo(getWordsValue(wordsResult, "有效期限止"));
            licenseInfo.setIssuingAuthority(getWordsValue(wordsResult, "发证机关"));

            return licenseInfo;
        } catch (Exception e) {
            System.out.println("解析驾驶证信息时发生错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 行驶证解析
     */
    /**
     * 解析行驶证识别结果
     *
     * @param vehicleLicenseResult 行驶证OCR识别结果JSON字符串
     * @return VehicleLicenseInfo 行驶证信息对象
     */
    public static VehicleLicenseInfo parseVehicleLicenseInfo(String vehicleLicenseResult) {
        try {
            // 将外层JSON字符串转换为Map
            Map<String, Object> outerMap = GsonUtils.fromJson(vehicleLicenseResult, Map.class);

            // 获取words_result部分
            Map<String, Object> wordsResult = (Map<String, Object>) outerMap.get("words_result");

            if (wordsResult == null || wordsResult.isEmpty()) {
                System.out.println("解析失败：未找到有效的识别结果");
                return null;
            }

            // 提取各个字段信息
            VehicleLicenseInfo licenseInfo = new VehicleLicenseInfo();
            licenseInfo.setPlateNumber(getWordsValue(wordsResult, "号牌号码"));
            licenseInfo.setVehicleType(getWordsValue(wordsResult, "车辆类型"));
            licenseInfo.setOwner(getWordsValue(wordsResult, "所有人"));
            licenseInfo.setAddress(getWordsValue(wordsResult, "住址"));
            licenseInfo.setUseCharacter(getWordsValue(wordsResult, "使用性质"));
            licenseInfo.setBrandModel(getWordsValue(wordsResult, "品牌型号"));
            licenseInfo.setVin(getWordsValue(wordsResult, "车辆识别代号"));
            licenseInfo.setEngineNumber(getWordsValue(wordsResult, "发动机号码"));
            licenseInfo.setRegisterDate(formatDate(getWordsValue(wordsResult, "注册日期")));
            licenseInfo.setIssueDate(formatDate(getWordsValue(wordsResult, "发证日期")));
            licenseInfo.setPassengerCapacity(getWordsValue(wordsResult, "核定载人数"));
            licenseInfo.setTotalWeight(getWordsValue(wordsResult, "总质量"));
            licenseInfo.setCurbWeight(getWordsValue(wordsResult, "整备质量"));

            return licenseInfo;
        } catch (Exception e) {
            System.out.println("解析行驶证信息时发生错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 日趋处理
     */
    public static String formatDate(String dateStr) {
        if (dateStr == null || dateStr.length() != 8) {
            System.out.println("无效的日期格式");
            return "未识别";
        }

        // 提取年、月、日部分
        String year = dateStr.substring(0, 4);
        String month = dateStr.substring(4, 6);
        String day = dateStr.substring(6, 8);

        // 拼接成目标格式
        return year + "-" + month + "-" + day;
    }
    private static String getWordsValue(Map<String, Object> wordsResult, String fieldName) {
        try {
            if (wordsResult.containsKey(fieldName)) {
                Map<String, Object> fieldMap = (Map<String, Object>) wordsResult.get(fieldName);
                return (String) fieldMap.get("words");
            }
        } catch (Exception e) {
            // 忽略异常，返回null
        }
        return "未识别";
    }
}